package com.ckw.question.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.cache.RedisCache;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;
import java.util.concurrent.ThreadLocalRandom;

@Configuration
@Slf4j
public class RedisConfiguration {

    @Bean
    @Primary
    public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
        // 默认缓存配置
        RedisCacheConfiguration defaultCacheConfig = RedisCacheConfiguration.defaultCacheConfig()
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));

        // 自定义 RedisCacheManager
        return new RedisCacheManager(
                RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory),
                defaultCacheConfig
        ) {
            @Override
            protected RedisCache createRedisCache(String name, RedisCacheConfiguration cacheConfig) {
                // 为每个缓存生成随机 TTL（600 秒上下浮动 60 秒）
                long randomTtl = generateRandomTtl(600, 60);
                log.info("Generated random TTL for cache '" + name + "': " + randomTtl + " seconds");

                // 创建带有随机 TTL 的缓存配置
                RedisCacheConfiguration randomTtlConfig = cacheConfig.entryTtl(Duration.ofSeconds(randomTtl));
                return super.createRedisCache(name, randomTtlConfig);
            }
        };
    }

    /**
     * 生成随机 TTL
     *
     * @param baseTtl     基础 TTL（例如 600 秒）
     * @param offsetRange 偏移范围（例如 60 秒）
     * @return 随机 TTL
     */
    private long generateRandomTtl(long baseTtl, long offsetRange) {
        // 使用 ThreadLocalRandom 生成随机数
        long offset = ThreadLocalRandom.current().nextLong(-offsetRange, offsetRange + 1);
        return baseTtl + offset;
    }
}